package com.rt.cloud.auth.config.response;

import com.rt.cloud.auth.facade.ShortTokenApi;
import com.rt.cloud.auth.facade.ShortTokenFacade;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

// 自定义spring security oauth /auth/token的返回内容格式
// https://blog.csdn.net/u013905744/article/details/100637224
// Vue调用，方法可行，但是swagger会有问题
@Component
@Aspect
public class AuthTokenAspect {

    @Resource
    ShortTokenFacade shortTokenFacade;

    private Logger logger = LoggerFactory.getLogger(getClass());

    /// @Around是可以改变controller返回值的
    @Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        // 放行
        Response response = new Response();
        Object proceed = pjp.proceed();
        if (proceed != null) {
            ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>)proceed;
            OAuth2AccessToken body = responseEntity.getBody();
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                // long token to short token
                String accessToken = body.getValue();
                String jti = (String) body.getAdditionalInformation().get("jti");
                shortTokenFacade.create(jti, accessToken);
                // serializer
                response.setObj(body).success();
            } else {
                logger.error("error:{}", responseEntity.getStatusCode().toString());
                response.fault("获取授权码失败");
            }
        }
        return ResponseEntity
                .status(200)
                .body(response);
    }
}
